//
//  AppDelegate.m
//  YMRTC
//
//  Created by admin on 2022/4/6.
//
#import "AppDelegate.h"
#import "LoginViewController.h"
#import "MainTabBarController.h"



@interface AppDelegate () <YMConnectionStatusDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    NSAssert(kYMAppKey.length > 0, @"请先配置译码小二郎 AppKey");
    NSAssert(kYMAppSecret.length > 0, @"请先配置译码小二郎 AppSecret");
    
    
    //1. 即时通讯SDK初始化
    YMIMConfig *config = [YMIMConfig configWithAppkey:kYMAppKey appsecret:kYMAppSecret];
    config.enableConsoleLog = YES;
    [[YMIMClient sharedClient] initSDKWithConfig:config];
    [YMIMClient sharedClient].connectionStatusDelegate = self;
    
    
    //2. 音视频通话SDK 初始化
    [[YMCallManager shared]registerAppKey:kYMAppKey appSecret:kYMAppSecret];


    
    [[UINavigationBar appearance] setBackgroundImage:[YMIMKitUtils imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    [self showLoginVC];
    [self.window makeKeyAndVisible];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterMain:) name:@"enterMain" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLoginVC) name:@"login" object:nil];

    
    return YES;
}


- (void)showLoginVC {
//    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginViewController *vc = [[LoginViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    self.window.rootViewController = nav;
}


- (void)onYMConnectionStatusChanged:(YMConnectStatusCode)status {
    
    if (status == YMConnectInvalidTokenOrTokenExpired) {
        [[YMIMClient sharedClient] logout];
    }else if (status == YMConnectUserLoginOnAnotherDevice) {
        [YMIMKitUtils showAlertWithTitle:@"" message:@"账号在另外一个设备上登录" from:self.window.rootViewController showCancel:NO confirmHandler:^{
            [[YMIMClient sharedClient] logout];
            [self showLoginVC];
        }];
    }
}




- (void)enterMain:(NSNotification *)notif {
    
    MainTabBarController *tabVC = [[MainTabBarController alloc] init];
    self.window.rootViewController = tabVC;
}

@end
